<?php 
include_once '../classes/design.php';
include_once '../classes/dao.php';

$design = new Design("..", "onbeforeunload='return confirmarSaida()'");
$design->adicionar_form("form_animacao");
$dao = new DAO();

if (isset($_REQUEST["id"])) {
	try {
		$animacao = $dao->get_animacao($_REQUEST["id"]);
	}
	catch (Exception $e) {
		header("Location: index.php?erro=".$e->getMessage());
	}
}
else {
	$animacao = new Animacao();
}

$design->imprimir_topo();
?>

<a href="index.php" class="titulo">Eventos</a><br/>

<script type="text/javascript" src="../javascript/funcoes.js"></script>
<script type="text/javascript" src="../javascript/validacao.js"></script>
<script type="text/javascript" src="../javascript/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../javascript/jquery-ui-1.8.17.custom.min.js"></script>
<script type="text/javascript" src="../javascript/date.format.js"></script>
<script type="text/javascript" src="../javascript/jquery.ui.datepicker-pt-BR.js"></script>
<script type="text/javascript" src="../javascript/jquery.colorbox.js"></script>
<script>
function adicionarMusicaLista(id, titulo, tom, quem_canta) {
	var wrapper = document.getElementById("sortable");
	var li = document.createElement("li");
	li.setAttribute("id", "musica_" + id);
	var table = document.createElement("table");
	table.setAttribute("align", "center");
	table.className = "tabelaOrdenavel";
	var tr = document.createElement("tr");
	var td1 = document.createElement("td");
	td1.setAttribute("width", "200");
	td1.innerHTML = "<a href=\"../musicas/form.php?id=" + id + "\">" + titulo + "</a>";
	td1.innerHTML += "<input type=\"hidden\" name=\"musica[]\" value=\"" + id + "\" />";
	var td2 = document.createElement("td");
	td2.setAttribute("width", "150");
	td2.setAttribute("align", "center");
	var select = document.createElement("select");
	select.setAttribute("name", "tom[]");
	<?php
		foreach (Musica::lista_tons() as $tom) {
			echo "
			 AddSelectOption(select, \"$tom\", \"$tom\", false);
			";
		}
	?>
	$(select).val(tom);
	td2.appendChild(select);
	var td3 = document.createElement("td");
	td3.setAttribute("width", "100");
	td3.setAttribute("align", "center");
	td3.innerHTML = "<input type=\"text\" name=\"quem_canta[]\" style=\"width: 100px;\" value=\"" + quem_canta + "\"/>";
	var td4 = document.createElement("td");
	td4.setAttribute("align", "center");
	td4.setAttribute("width", "100");
	td4.innerHTML = "<a href=\"javascript: void(0);\" onclick=\"javascript: removerMusica(" + id + ")\"><img src=\"<?php echo $design->get_endereco_imagem("excluir.gif");?>\" /></a>";
	tr.appendChild(td1);
	tr.appendChild(td2);
	tr.appendChild(td3);
	tr.appendChild(td4);
	table.appendChild(tr);
	li.appendChild(table);
	wrapper.appendChild(li);
}

function removerMusica(id) {
	var wrapper = document.getElementById("sortable");
	var elemento = document.getElementById("musica_" + id);
	wrapper.removeChild(elemento);
}

function adicionarMusicaForm(id, titulo, tom, quem_canta) {
	$("#nova_musica_id").val("");
	$("#nova_musica").val("");
	$("#novo_tom").val("");
	$("#novo_quem_canta").val("");
	adicionarMusicaLista(id, titulo, tom, quem_canta);
}

function botaoAdicionar() {
	var id = $("#nova_musica_id").val();
	if (id != "") {
		var titulo = $("#nova_musica").val();
		var tom = $("#novo_tom").val();
		var quem_canta = $("#novo_quem_canta").val();
		adicionarMusicaForm(id, titulo, tom, quem_canta);
	}
}

$(function() {
	var dates = $("#data_inicio, #data_fim").datepicker({
		dateFormat: 'dd/mm/yy',
		changeMonth: true,
		changeYear: true,
		yearRange: 'c-5:c+5',
		onClose: function() {
			desselecionar(this);
		},
		onSelect: function(selectedDate) {
			var dia = selectedDate.substring(0, 2);
			var mes = selectedDate.substring(3, 5);
			var ano = selectedDate.substring(6, 10);
			var dataSelecionada = new Date(mes + "-" + dia + "-" + ano);
			var option;
			if (this.id == "data_inicio") {
				option =  "minDate";
				dataSelecionada.setDate(dataSelecionada.getDate() + 1);
			}
			else {
				option = "maxDate";
				dataSelecionada.setDate(dataSelecionada.getDate() - 1);
			}
			data = dataSelecionada.format('dd/mm/yyyy');
			dates.not(this).datepicker("option", option, data);
		}
	});
});

$(function() {
	$( "#sortable" ).sortable({
		cursor: 'n-resize',
		opacity: 0.6,
		items: 'li:not(#titulos)'
	});
	$( "#sortable" ).disableSelection();
});

function limparMusica() {
	if ($("#nova_musica").val() == "") {
		$("#nova_musica_id").val("");
		$("#novo_tom").val($('option:first', "#novo_tom").val(""));
	}
}

$(document).ready(function() {
	$("#procurar").colorbox({
		href: "../musicas/procurar.php",
		iframe: true, 
		width: "75%", 
		height: "80%",
		fixed: true,
		opacity: 0.8});
	$("#nova_musica").autocomplete({
		source: "../servicos/procurar_musicas.php",
		minLength: 2,
		delay: 0,
		change: function (event, ui) {
			if (!ui.item) {
				$("#nova_musica").val("");
				limparMusica();
			}
		},
		focus: function (event, ui) {
			$("#nova_musica_id").val(ui.item.id);
			$("#novo_tom").val(ui.item.tom);
		},
		close: function (event, ui) {
			limparMusica();
		}
	});
	$('#nova_musica').blur(function () {
		limparMusica();
	});
});
</script>

<style>
#sortable { list-style-type: none; }
</style>

<?php 
if (isset($erro)) {
	echo "<div class=\"erro\">$erro</div>";
}

echo "
 <table border=\"0\" style=\"width: 90%; padding: 0px;\" align=\"center\">
 	<tr valign=\"top\">
 		<td>
 			<form method=\"post\" action=\"salvar_animacao.php\" id=\"form_animacao\" style=\"display: inline;\">
				<input type=\"hidden\" name=\"id\" value=\"".$animacao->get_id()."\" />
				<table border=\"0\" align=\"center\" style=\"width: 100%; margin: 0px;\">
";
if ($animacao->get_quem_mexeu() != "") {
	echo "
					<tr valign=\"top\">
						<td align=\"right\" colspan=\"2\"><i>Última alteração: ".$animacao->get_quando_mexeu()." por ".$animacao->get_quem_mexeu()."</i></td>
					</tr>
	";
}
echo "
					<tr valign=\"top\">
						<td align=\"right\" style=\"width: 200px;\"><b>Nome do Evento: *</b></td>
						<td><input type=\"text\" name=\"nome\" value=\"".htmlentities($animacao->get_nome(), ENT_QUOTES, "UTF-8")."\" style=\"width: 100%;\" alt=\"Nome do Evento|Obrig\" />
					</tr>
					<tr valign=\"top\">
						<td align=\"right\"><b>Local:</b></td>
						<td><input type=\"text\" name=\"local\" value=\"".htmlentities($animacao->get_local(), ENT_QUOTES, "UTF-8")."\" style=\"width: 100%;\" />
					</tr>
					<tr valign=\"top\">
						<td align=\"right\"><b>Data de início: *</b></td>
						<td><input type=\"text\" name=\"data_inicio\" id=\"data_inicio\" value=\"".$animacao->get_data_inicio_formatada()."\" alt=\"Data de início|Obrig|Data|NN/NN/NNNN\" onkeyup=\"preencher(this, 'NN/NN/NNNN', event);\" /></td>
					</tr>
					<tr valign=\"top\">
						<td align=\"right\"><b>Data de término:</b></td>
						<td>
							<input type=\"text\" name=\"data_fim\" id=\"data_fim\" value=\"".$animacao->get_data_fim_formatada()."\" alt=\"Data de término|Opcional|DataComparacao.Depois.data_inicio|NN/NN/NNNN\" onkeyup=\"preencher(this, 'NN/NN/NNNN', event);\"/><br/>
							(só necessário se o evento durar mais de um dia)
						</td>
					</tr>
					<tr valign=\"top\">
						<td align=\"right\"><b>Descrição:</b></td>
						<td><textarea name=\"descricao\" style=\"width: 100%; height: 50px;\">".$animacao->get_descricao()."</textarea></td>
					</tr>
					<tr valign=\"top\">
						<td align=\"right\"><b>Músicas:</b></td>
						<td>
							Clique e arraste para ordenar<br/>
							<ul id=\"sortable\">
								<li id=\"titulos\">
									<table align=\"center\">
										<tr>
											<th width=\"200\">Música</th>
											<th width=\"150\">Tom</th>
											<th width=\"100\">Cantada por</th>
											<th width=\"100\">Remover</th>
										</tr>
									</table>
								</li>
";
foreach ($animacao->get_musicas_animacao() as $musica_animacao) {
	$musica = $musica_animacao->get_musica();
	$tom = $musica_animacao->get_tom();
	$quem_canta = $musica_animacao->get_quem_canta();
	echo "
								<li id=\"musica_".$musica->get_id()."\">
									<table class=\"tabelaOrdenavel\" align=\"center\">
										<tr>
											<td width=\"200\">
												<a href=\"../musicas/form.php?id=".$musica->get_id()."\">".$musica->get_titulo()."</a>
												<input type=\"hidden\" name=\"musica[]\" value=\"".$musica->get_id()."\" />
											</td>
											<td width=\"150\" align=\"center\">
												<select name=\"tom[]\">
	";
	foreach (Musica::lista_tons() as $possivel_tom) {
		echo "<option value=\"$possivel_tom\"";
		if ($possivel_tom == $tom) {
			echo " selected";
		}
		echo ">$possivel_tom</option>";
	}
	echo "
												</select>
											</td>
											<td width=\"100\" align=\"center\">
												<input type=\"text\" name=\"quem_canta[]\" style=\"width: 100px;\" value=\"$quem_canta\" />
											</td>
											<td width=\"100\" align=\"center\">
												<a href=\"javascript: void(0);\" onclick=\"javascript: removerMusica(".$musica->get_id().")\">".$design->get_imagem("excluir.gif")."</a>
											</td>
										</tr>
									</table>
								</li>
	";
}
echo "			
							</ul>
						</td>
					</tr>
				</table>
 			</form>
 		</td>
 		<td>
";
if ($animacao->get_id() != "") {
echo "	
 			<div class=\"lateral\" style=\"white-space: nowrap;\">
 				<a href=\"folha.php?id=".$animacao->get_id()."\">".$design->get_imagem("folha.png")." Folha de cantos</a>
 			</div>
";
}
echo "
 		</td>
 	</tr>
 	<tr>
 		<td>
			 <form name=\"nova_musica_form\" id=\"nova_musica_form\" action=\"\" method=\"post\" onSubmit=\"javascript: botaoAdicionar(); return false;\">
			 	<table border=\"0\" align=\"center\" style=\"width: 100%; margin: 0px;\">
			 		<tr>
			 			<td rowspan=\"2\" style=\"width: 200px;\"></td>
			 			<td colspan=\"5\">
			 				".$design->get_imagem("mais.gif")." Adicionar música:
			 			</td>
			 		</tr>
					<tr>
						<td align=\"center\" width=\"200\">
							<input type=\"hidden\" name=\"nova_musica_id\" id=\"nova_musica_id\"/>
							Música<br/>
							<input type=\"text\" name=\"nova_musica\" id=\"nova_musica\"/>
						</td>
						<td align=\"center\" width=\"80\">
							Tom<br/>
							<select name=\"novo_tom\" id=\"novo_tom\">
";
foreach (Musica::lista_tons() as $possivel_tom) {
	echo "<option value=\"$possivel_tom\">$possivel_tom</option>";
}
echo "
							</select>
						</td>
						<td align=\"center\" width=\"100\">
							Cantada por<br/> 
							<input type=\"text\" name=\"novo_quem_canta\" id=\"novo_quem_canta\"/>
						</td>
						<td align=\"center\">
							Adicionar<br/>
							<button type=\"submit\">Adicionar</button>
						</td>
						<td align=\"center\">
							Procurar<br/>
							<button type=\"button\" id=\"procurar\">
								".$design->get_imagem("search.png", "Procurar música")."
							</button>
						</td>
					</tr>
				</table>
			</form>
		</td>
	</tr>
";
echo "
	<tr>
		<td align=\"center\" colspan=\"2\">
			<button type=\"button\" onclick=\"javascript: submeterForm('form_animacao');\">Salvar</button>
			<button type=\"button\" onclick=\"javascript: window.location.href='index.php'\">Cancelar</button>
";
if ($animacao->get_id() != "") {
	echo "<button type=\"button\" onclick=\"javascript: confirmarExclusaoEvento(".$animacao->get_id().", '".addslashes(htmlspecialchars($animacao->get_nome()))."', 'Animacao');\">Excluir</button>";
}
echo "
		</td>
	</tr>
</table>
";
?>


<?php 
$design->imprimir_fim();
?>